package com.deyou.activity;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.adapter.HouseSearchResultAdapter;
import com.deyou.adapter.SearchCityAdapter;
import com.deyou.adapter.SearchHouseAdapter;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.CityBean;
import com.deyou.model.CityDataSupport;
import com.deyou.model.LzyResponse;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.crud.callback.SaveCallback;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class HouseSearchListActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.edt_search_key)
    EditText edtSearchKey;
    @BindView(R.id.btn_cancel_search)
    TextView btnCancelSearch;
    @BindView(R.id.search_recycler_view)
    RecyclerView searchRecyclerView;
    private InputMethodManager imm;

    private SearchHouseAdapter mAdapter;
    private List<CityBean> listData = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_search_list);
        ButterKnife.bind(this);
        initView();
    }

    private void initView(){
        searchRecyclerView.setItemAnimator(new DefaultItemAnimator());
        searchRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        mAdapter = new SearchHouseAdapter(this);
        searchRecyclerView.setAdapter(mAdapter);

        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        edtSearchKey.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    searchDataByKey();
                }
                return false;
            }
        });

        mAdapter.setOnItemClickListener(this);
    }
    
    @OnClick(R.id.btn_cancel_search)
    public void onViewClicked() {
        finish();
    }

    private void searchDataByKey(){
        JSONObject object = new JSONObject();
        try {
            object.put("suggest", URLEncoder.encode(edtSearchKey.getText().toString(), "UTF-8"));
            String paramJson = object.toString();
            Logger.i(Logger.LOGTAG + "搜索数据", paramJson);

            Type type = new TypeToken<LzyResponse<List<CityBean>>>() {}.getType();
            ServerApi.<LzyResponse<List<CityBean>>>getData(type, Urls.searchDataByKey, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading("获取数据中...");
                        }
                    })//
                    .map(new Function<LzyResponse<List<CityBean>>, List<CityBean>>() {
                        @Override
                        public List<CityBean> apply(@NonNull LzyResponse<List<CityBean>> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<List<CityBean>>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull List<CityBean> cityBean) {
                            if (null != cityBean && cityBean.size() > 0){
                                mAdapter.setNewData(cityBean);
                                listData = cityBean;
                            } else {
                                mAdapter.setNewData(null);
                                Bundle bundle = new Bundle();
                                bundle.putString("keywords", edtSearchKey.getText().toString());
                                bundle.putString("lonAndLat", "");
                                bundle.putString("regionCode", "");
                                AndroidUtils.startNextActivity(HouseSearchListActivity.this, HouseSearchResultListActivity.class, bundle, false);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (null != listData && listData.size() > 0 && null != listData.get(position)){
            CityBean searchData = listData.get(position);
            Bundle bundle = new Bundle();
            bundle.putString("lonAndLat", "");
            bundle.putString("regionCode", listData.get(position).resourceId);
            if (searchData.resourceType == 1){
                AndroidUtils.startNextActivity(HouseSearchListActivity.this, HouseResourceDetailActivity.class, bundle, false);
            } else if (searchData.resourceType == 2){
                AndroidUtils.startNextActivity(HouseSearchListActivity.this, HouseSearchResultListActivity.class, bundle, false);
            }
            saveSearchHistory(searchData);
            finish();
        }
    }

    private void saveSearchHistory(CityBean searchData) {
        CityDataSupport city = new CityDataSupport();
        city.regionId = searchData.resourceId;
        city.regionName = searchData.resourceName;
        city.userId = SPUtils.getStringByKey(HouseSearchListActivity.this, Constants.UserId);
        city.type = searchData.resourceType;
        List<CityDataSupport> cityData = DataSupport.where("regionId=? and userId=?", searchData.resourceId, SPUtils.getStringByKey(HouseSearchListActivity.this, Constants.UserId)).find(CityDataSupport.class);
        if (null == cityData || cityData.size() <= 0) {
            city.saveAsync().listen(new SaveCallback() {
                @Override
                public void onFinish(boolean success) {
                    Logger.i(Logger.LOGTAG + "保存记录", success + "");
                }
            });
        }
    }
}
